﻿namespace Snipps.Views
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Windows;
    using System.Windows.Input;

    using GlobalHotKey;

    using Snipps.Langs;
    using Snipps.ViewModels;

    public partial class MainWindow : Window
    {
        private readonly List<HotKey> _alternativeGlobalHotKeys;

        private readonly HotKeyManager _hotKeyManager;

        private HotKey _globalHotKey;

        public MainWindow()
        {
            _hotKeyManager = new HotKeyManager();
            _globalHotKey = new HotKey(Key.Space, ModifierKeys.Windows);

            _alternativeGlobalHotKeys = new List<HotKey>();
            _alternativeGlobalHotKeys.Add(new HotKey(Key.Space, ModifierKeys.Alt));
            _alternativeGlobalHotKeys.Add(new HotKey(Key.Space, ModifierKeys.Alt | ModifierKeys.Control));

            InitializeComponent();
            Closing += (s, e) => ViewModelLocator.Cleanup();

            _hotKeyManager.KeyPressed += HotKeyManagerPressed;

            TryRegisterGlobalHotKey(_globalHotKey);
        }

        private void TryRegisterGlobalHotKey(HotKey key)
        {
            try
            {
                _hotKeyManager.Register(key);
            }
            catch (Exception)
            {
                if (_alternativeGlobalHotKeys.Any())
                {
                    key = _alternativeGlobalHotKeys.First();
                    _alternativeGlobalHotKeys.Remove(key);
                    TryRegisterGlobalHotKey(key);
                }
                else
                {
                    key = null;
                }
            }

            if (key != null)
            {
                if (!Equals(_globalHotKey, key))
                {
                    _globalHotKey = key;

                    var msg = Lang.FollowingAlternativeGlobalKeyUsed + key.Modifiers + " + " + key.Key;

                    // TODO: refactor this to notifyuserservice
                    MessageBox.Show(this, msg, string.Empty, MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            else
            {
                _globalHotKey = null;
                MessageBox.Show(this, Lang.CannotRegisterGlobalKey, string.Empty, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void HotKeyManagerPressed(object sender, KeyPressedEventArgs e)
        {
            var dc = DataContext as MainViewModel;
            if (dc != null)
            {
                dc.ToggleVisibilityCommand.Execute(null);
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (_globalHotKey != null)
            {
                _hotKeyManager.Unregister(_globalHotKey);
            }

            base.OnClosing(e);
        }
    }
}